package cn.gjxblog.mq.pattern.direct;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author gjx
 * @version v1.0
 * @Description
 * @date 2019/7/4 11:48
 */
public class Consumer {
    public static void main(String[] args) throws Exception {
        //1 创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("www.alserver.com");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("123456");
        //2 创建连接
        Connection connection = connectionFactory.newConnection();

        //3 通过connection创建channel
        Channel channel = connection.createChannel();

        //4 声明一个队列
        String queueName = "test001";
        channel.queueDeclare(queueName,true,false,false,null);

        //5 创建消费者
        QueueingConsumer queueingConsumer = new QueueingConsumer(channel);

        //6 设置chanel
        channel.basicConsume(queueName,true,queueingConsumer);

        //7 获取消息
        QueueingConsumer.Delivery deliver = queueingConsumer.nextDelivery();
        String msg = new String(deliver.getBody());
        System.out.println("msg is:"+msg);

        //5 关闭相关连接
        channel.close();
        connection.close();
    }
}
